package com.xiaoyuan.minicore.aop;

import java.lang.reflect.Method;
import java.util.List;

import net.sf.cglib.proxy.MethodProxy;

/**
 * @Auther: xiaoyuan
 * @Date: 2020/4/30
 * @Description:
 */
public class Chain {

    private List<Handler> list;
    private int index = -1;

    private Object proxy;
    private Method methodTarget;
    private Object[] args;
    private MethodProxy methodProxy;

    public Chain(List<Handler> list, Object proxy, Method methodTarget, Object[] args, MethodProxy methodProxy) {
        this.list = list;
        this.proxy = proxy;
        this.methodTarget = methodTarget;
        this.args = args;
        this.methodProxy = methodProxy;
    }

    public Object proceed() throws Throwable {
        Object result;
        if (++index == list.size()) {
            result = methodProxy.invokeSuper(proxy, args);
        } else {
            Handler handler = list.get(index);
            result = handler.proceed(this);
        }
        return result;
    }

    public Method getMethodTarget() {
        return methodTarget;
    }

    public Object[] getArgs() {
        return args;
    }

}
